Popular Searches
Popular Course Categories
Popular Courses

Working with Arrays, Lists, Sets, and Maps

Working with Arrays, Lists, Sets, and Maps

Kotlin Programming Fundamentals for Android

Working with Arrays, Lists, Sets, and Maps in Kotlin

Course: Android App Development

Topic: Working with Arrays, Lists, Sets, and Maps

Course Link: Android App Development Course

Demo Link: Register for a Course Demo

JustAcademy Homepage: Visit JustAcademy


1. Introduction to Arrays and Collections

Arrays and collections are essential data structures in Kotlin programming. They allow developers to store, organize, retrieve, update, and process multiple values efficiently instead of creating a separate variable for every value.

In Android development, arrays and collections are used to manage contact lists, product catalogs, student records, API responses, user preferences, search results, application settings, and other groups of data.

Kotlin provides arrays as well as collection types such as Lists, Sets, and Maps. Each structure serves a different purpose and offers different operations.

Real-World Examples

  • Array: Store a fixed number of quiz scores.
  • List: Store a sequence of product names or search results.
  • Set: Store unique category names or selected item identifiers.
  • Map: Store settings as key-value pairs, such as a theme name and its selected value.

2. Understanding Arrays in Kotlin

An array is a data structure that stores a fixed number of elements. The elements are ordered and accessed using numeric indexes that begin at zero.

Kotlin provides the generic Array<T> type and specialized arrays such as IntArray, DoubleArray, BooleanArray, and CharArray.

Creating an Array

fun main() {
    val numbers = arrayOf(10, 20, 30, 40, 50)

    println(numbers[0])
    println(numbers[2])
    println(numbers.size)
}

Output:

10
30
5

Here, arrayOf() creates an array containing five integers. The expression numbers[0] accesses the first element, while numbers.size returns the total number of elements.

Declaring Arrays with Specific Types

val names: Array<String> = arrayOf("Aarav", "Priya", "Rohan")
val marks: IntArray = intArrayOf(85, 90, 78)
val prices: DoubleArray = doubleArrayOf(99.5, 149.0, 250.75)
val flags: BooleanArray = booleanArrayOf(true, false, true)

Using a specific type helps the compiler detect incompatible values and makes the intended data structure easier to understand.

Creating an Empty Array

val emptyNames = emptyArray<String>()
val emptyNumbers = IntArray(0)

Use an empty array when an API or function requires an array but no elements are currently available.

3. Accessing and Updating Array Elements

Array elements can be accessed and updated using the indexed access operator, represented by square brackets [].

Accessing Elements

val languages = arrayOf("Kotlin", "Java", "Python")

println(languages[0])
println(languages[1])
println(languages[2])

Output:

Kotlin
Java
Python

Updating Elements

fun main() {
    val scores = intArrayOf(70, 80, 90)

    scores[1] = 85

    println(scores.joinToString())
}

Output:

70, 85, 90

Although the array variable is declared with val, its elements can still be modified. The val keyword prevents reassignment of the array reference, not modification of the array's contents.

Important Array Properties

Property or Function Purpose Example
size Returns the number of elements. numbers.size
indices Returns the valid index range. numbers.indices
lastIndex Returns the last valid index. numbers.lastIndex
first() Returns the first element when the array is not empty. numbers.first()
last() Returns the last element when the array is not empty. numbers.last()
isEmpty() Checks whether the array contains no elements. numbers.isEmpty()
contains() Checks whether an element exists. numbers.contains(20)
joinToString() Creates a readable string representation. numbers.joinToString()

4. Iterating Through Arrays

Iteration means visiting each element in a data structure. Kotlin supports several convenient ways to iterate over arrays.

Using a For Loop

val fruits = arrayOf("Apple", "Banana", "Orange")

for (fruit in fruits) {
    println(fruit)
}

Using Indexes

val scores = intArrayOf(70, 80, 90)

for (index in scores.indices) {
    println("Index $index: ${scores[index]}")
}

Output:

Index 0: 70
Index 1: 80
Index 2: 90

Using forEach

val numbers = arrayOf(2, 4, 6, 8)

numbers.forEach { number ->
    println(number * 2)
}

Use a direct loop when it improves readability, and use indexed iteration when the position of each element matters.

5. Common Array Operations

Searching for an Element

val names = arrayOf("Aarav", "Priya", "Rohan")

println(names.contains("Priya"))
println(names.indexOf("Rohan"))

Output:

true
2

Sorting an Array

val numbers = intArrayOf(40, 10, 30, 20)

numbers.sort()

println(numbers.joinToString())

Output:

10, 20, 30, 40

The sort() function sorts the existing array. If the original order must be preserved, create a copy before sorting.

Filtering and Transforming Array Data

val numbers = arrayOf(1, 2, 3, 4, 5, 6)

val evenNumbers = numbers.filter { it % 2 == 0 }
val doubledNumbers = numbers.map { it * 2 }

println(evenNumbers)
println(doubledNumbers)

Output:

[2, 4, 6]
[2, 4, 6, 8, 10, 12]

Functions such as filter() and map() return new lists rather than changing the original array.

6. Understanding Lists in Kotlin

A List is an ordered collection of elements. Lists allow duplicate values and provide access to elements by their indexes. Unlike arrays, mutable lists can grow or shrink as elements are added or removed.

Kotlin provides two main list interfaces:

  • List: Provides read-only collection operations through that reference.
  • MutableList: Provides operations for adding, removing, and updating elements.

Creating a Read-Only List

val languages = listOf("Kotlin", "Java", "Python")

println(languages)
println(languages[0])
println(languages.size)

Output:

[Kotlin, Java, Python]
Kotlin
3

A Kotlin List reference does not expose methods for changing its elements. However, read-only does not automatically guarantee that no other reference can modify the underlying collection.

Creating a Mutable List

fun main() {
    val fruits = mutableListOf("Apple", "Banana", "Orange")

    fruits.add("Mango")
    fruits.remove("Banana")
    fruits[0] = "Grapes"

    println(fruits)
}

Output:

[Grapes, Orange, Mango]

7. Adding and Removing List Elements

Mutable lists provide methods for managing elements dynamically.

Method Purpose Example
add(element) Adds an element to the list. items.add("Laptop")
add(index, element) Inserts an element at a position. items.add(1, "Phone")
addAll(collection) Adds multiple elements. items.addAll(newItems)
remove(element) Removes a matching element. items.remove("Laptop")
removeAt(index) Removes the element at an index. items.removeAt(0)
clear() Removes all elements. items.clear()
set(index, element) Updates the element at an index. items.set(0, "Tablet")

Example: Managing a Shopping List

fun main() {
    val shoppingList = mutableListOf("Milk", "Bread", "Eggs")

    shoppingList.add("Rice")
    shoppingList.add(1, "Butter")
    shoppingList.remove("Eggs")

    println(shoppingList)
}

Output:

[Milk, Butter, Bread, Rice]

8. Searching, Filtering, and Sorting Lists

Finding an Element

val students = listOf("Aarav", "Priya", "Rohan", "Meera")

println(students.contains("Priya"))
println(students.indexOf("Meera"))
println(students.first())
println(students.last())

Filtering a List

val marks = listOf(45, 80, 32, 90, 65)

val passingMarks = marks.filter { it >= 40 }

println(passingMarks)

Output:

[45, 80, 90, 65]

Transforming List Elements

val prices = listOf(100, 200, 300)

val discountedPrices = prices.map { it * 0.9 }

println(discountedPrices)

Output:

[90.0, 180.0, 270.0]

Sorting a List

val numbers = listOf(50, 10, 40, 20, 30)

val ascending = numbers.sorted()
val descending = numbers.sortedDescending()

println(ascending)
println(descending)

Output:

[10, 20, 30, 40, 50]
[50, 40, 30, 20, 10]

Functions such as filter(), map(), and sorted() return transformed collections. They do not directly mutate the original list.

9. Understanding Sets in Kotlin

A Set is a collection that stores unique elements. It is useful when duplicate values are not required, such as unique usernames, selected tags, product categories, or identifiers.

Kotlin provides:

  • Set: A read-only interface for accessing unique elements.
  • MutableSet: A mutable interface that supports adding and removing elements.

Creating a Set

val numbers = setOf(10, 20, 30, 20, 10)

println(numbers)
println(numbers.size)

Typical output for the default insertion-preserving implementation:

[10, 20, 30]
3

Duplicate values are eliminated when the Set is constructed. The exact iteration order depends on the implementation, so do not assume that every Set is ordered.

Creating a Mutable Set

fun main() {
    val skills = mutableSetOf("Kotlin", "Java")

    skills.add("Android")
    skills.add("Kotlin")
    skills.remove("Java")

    println(skills)
}

Typical output:

[Kotlin, Android]

The second attempt to add Kotlin does not create a duplicate element.

10. Common Set Operations

Checking Whether an Element Exists

val categories = setOf("Education", "Technology", "Business")

println("Technology" in categories)
println("Sports" in categories)

Output:

true
false

Combining Sets

val firstSet = setOf(1, 2, 3)
val secondSet = setOf(3, 4, 5)

val union = firstSet union secondSet
val intersection = firstSet intersect secondSet
val difference = firstSet subtract secondSet

println(union)
println(intersection)
println(difference)

Typical output:

[1, 2, 3, 4, 5]
[3]
[1, 2]
  • Union: Combines the unique elements of both sets.
  • Intersection: Returns the elements present in both sets.
  • Difference: Returns the elements in the first set that are not in the second.

Removing Duplicates from a List

val names = listOf("Aarav", "Priya", "Aarav", "Meera", "Priya")

val uniqueNames = names.toSet()

println(uniqueNames)

Typical output:

[Aarav, Priya, Meera]

Use distinct() when you want to remove duplicate values while keeping the first occurrence order in the resulting list:

val uniqueNames = names.distinct()
println(uniqueNames)

11. Understanding Maps in Kotlin

A Map stores data as key-value pairs. Every key is unique, while values may be repeated. Maps are useful when a value must be retrieved using a meaningful key instead of a numeric position.

For example, an application might associate a student's ID with a name, a product code with a price, or a settings key with a preference value.

Kotlin provides:

  • Map: A read-only interface for accessing key-value pairs.
  • MutableMap: A mutable interface for adding, updating, and removing entries.

Creating a Map

val student = mapOf(
    "name" to "Priya",
    "course" to "Android Development",
    "city" to "Mumbai"
)

println(student["name"])
println(student["course"])

Output:

Priya
Android Development

The to notation creates key-value pairs. The expression student["name"] retrieves the value associated with the key name.

Creating a Mutable Map

fun main() {
    val prices = mutableMapOf(
        "Laptop" to 50000,
        "Phone" to 20000
    )

    prices["Tablet"] = 15000
    prices["Phone"] = 22000
    prices.remove("Laptop")

    println(prices)
}

Typical output:

{Phone=22000, Tablet=15000}

Adding a new key creates an entry. Assigning a value to an existing key updates that entry rather than creating a duplicate key.

12. Accessing and Updating Map Values

Accessing a Value by Key

val user = mapOf(
    "username" to "aarav",
    "email" to "[email protected]"
)

println(user["username"])
println(user["email"])
println(user["phone"])

The first two expressions return their associated values. The missing key returns null because the map does not contain a corresponding entry.

Checking Whether a Key Exists

val settings = mapOf(
    "darkMode" to true,
    "notifications" to false
)

println("darkMode" in settings)
println(settings.containsKey("language"))
println(settings.containsValue(true))

Output:

true
false
true

Iterating Through a Map

val scores = mapOf(
    "Aarav" to 85,
    "Priya" to 92,
    "Rohan" to 78
)

for ((name, score) in scores) {
    println("$name scored $score")
}

This loop uses destructuring to access each key and its corresponding value.

Working with Keys and Values

val prices = mapOf(
    "Book" to 250,
    "Pen" to 20,
    "Bag" to 900
)

println(prices.keys)
println(prices.values)
println(prices.entries)

The keys, values, and entries properties provide views of the keys, values, and key-value entries, respectively.

13. Useful Map Operations

Operation Purpose Example
map[key] Retrieves a value for a key, or null when no mapping exists. prices["Book"]
containsKey(key) Checks whether a key exists. prices.containsKey("Book")
containsValue(value) Checks whether a value exists. prices.containsValue(250)
put(key, value) Adds or updates an entry in a mutable map. prices.put("Pen", 25)
remove(key) Removes an entry by key. prices.remove("Book")
getOrDefault(key, default) Gets a value or a default when the key is absent. prices.getOrDefault("Pencil", 10)
getOrPut(key) { value } Gets an existing value or inserts a calculated default in a mutable map. counts.getOrPut("Kotlin") { 0 }
toMap() Creates a read-only map copy of entries. mutablePrices.toMap()

Counting Occurrences with a Map

fun main() {
    val words = listOf("Kotlin", "Java", "Kotlin", "Python", "Java", "Kotlin")
    val counts = mutableMapOf<String, Int>()

    for (word in words) {
        counts[word] = (counts[word] ?: 0) + 1
    }

    println(counts)
}

Typical output:

{Kotlin=3, Java=2, Python=1}

This example demonstrates a common use of maps: storing a calculated value against a unique key.

14. Comparing Arrays, Lists, Sets, and Maps

Feature Array List Set Map
Stores Elements Elements Unique elements Key-value pairs
Access method Index Index Membership lookup Key lookup
Duplicates Allowed Allowed Not allowed for equal elements Keys are unique; values can repeat
Order Ordered by index Ordered Depends on implementation Depends on implementation
Resizable No; fixed size MutableList can grow or shrink MutableSet can grow or shrink MutableMap can grow or shrink
Example creation arrayOf(1, 2) listOf(1, 2) setOf(1, 2) mapOf("a" to 1)
Typical use Fixed-size data Ordered records Unique values Lookup by key

15. Mutable and Read-Only Collections

Kotlin separates read-only collection interfaces from mutable collection interfaces. This distinction helps communicate whether a reference should expose operations that modify the collection.

Read-Only Interface Mutable Interface Example
List<T> MutableList<T> Ordered collection of items
Set<T> MutableSet<T> Collection of unique items
Map<K, V> MutableMap<K, V> Key-value associations

Example

val readOnlyNames: List<String> = listOf("Aarav", "Priya")

val mutableNames: MutableList<String> =
    mutableListOf("Aarav", "Priya")

mutableNames.add("Rohan")

println(readOnlyNames)
println(mutableNames)

A read-only interface prevents modifications through that reference, but it does not necessarily mean that the underlying object is immutable. If another mutable reference points to the same collection, it may still change the contents.

Use val for references that should not be reassigned. Remember that val alone does not make an array or mutable collection immutable.

16. Converting Between Arrays and Collections

Android applications often receive arrays from APIs or libraries but need lists, sets, or maps for processing. Kotlin provides conversion functions to make this easier.

Array to List

val array = arrayOf("Kotlin", "Java", "Python")
val languageList = array.toList()

println(languageList)

Array to Set

val array = arrayOf("Red", "Blue", "Red", "Green")
val uniqueColors = array.toSet()

println(uniqueColors)

List to Mutable List

val original = listOf(10, 20, 30)
val mutableNumbers = original.toMutableList()

mutableNumbers.add(40)

println(mutableNumbers)

List to Map

val names = listOf("Aarav", "Priya", "Rohan")
val nameLengths = names.associateWith { it.length }

println(nameLengths)

Output:

{Aarav=5, Priya=5, Rohan=5}

Conversion functions such as toList() and toSet() create a new collection containing the converted elements. These are generally shallow copies, so referenced objects inside the collection are not automatically cloned.

17. Working with Collections in Android Applications

Arrays and collections are widely used in Android application logic, including Jetpack Compose interfaces, ViewModels, repositories, adapters, local data processing, and API responses.

Example 1: Displaying a List of Products

data class Product(
    val id: Int,
    val name: String,
    val price: Double
)

fun main() {
    val products = listOf(
        Product(1, "Keyboard", 1200.0),
        Product(2, "Mouse", 600.0),
        Product(3, "Monitor", 8500.0)
    )

    products.forEach { product ->
        println("${product.name}: ${product.price}")
    }
}

In Android, this product list could provide the data for a RecyclerView adapter or a Jetpack Compose LazyColumn.

Example 2: Filtering Products by Price

val affordableProducts = products.filter { product ->
    product.price < 2000
}

affordableProducts.forEach { product ->
    println(product.name)
}

Output:

Keyboard
Mouse

Example 3: Storing Unique Selected Categories

val selectedCategories = mutableSetOf<String>()

selectedCategories.add("Electronics")
selectedCategories.add("Books")
selectedCategories.add("Electronics")

println(selectedCategories.size)

Output:

2

A Set prevents duplicate category values from being stored. For selectable UI elements, the application can add or remove categories as users interact with the screen.

Example 4: Managing User Settings

val settings = mutableMapOf(
    "darkMode" to true,
    "notifications" to false
)

settings["notifications"] = true

println(settings["darkMode"])
println(settings["notifications"])

Maps are convenient for simple in-memory settings. For persistent preferences, use Android's DataStore or another suitable persistence mechanism rather than assuming an ordinary map survives application termination.

18. Collection Operations: map, filter, and reduce

Kotlin provides higher-order functions that make collection processing concise and expressive.

Using map()

The map() function transforms each element and returns a new list containing the transformed results.

val numbers = listOf(1, 2, 3, 4)
val doubled = numbers.map { it * 2 }

println(doubled)

Output:

[2, 4, 6, 8]

Using filter()

The filter() function returns the elements that satisfy a condition.

val numbers = listOf(10, 15, 20, 25, 30)
val filtered = numbers.filter { it >= 20 }

println(filtered)

Output:

[20, 25, 30]

Using reduce()

The reduce() function combines elements into one result. It requires a non-empty collection.

val numbers = listOf(10, 20, 30, 40)
val total = numbers.reduce { accumulator, number ->
    accumulator + number
}

println(total)

Output:

100

For potentially empty collections, consider fold() with an initial value or a suitable function such as sum() when it fits the data type.

19. Common Mistakes and Troubleshooting

Problem Cause Solution
Array index out of bounds Accessing an index outside the valid range. Check indices or validate the index before access.
Trying to add an element to an array Arrays have a fixed size. Use a mutable list when the number of elements must change.
Duplicate values appear in a collection A List allows duplicates. Use a Set or call distinct() if uniqueness is required.
Unexpected map value An existing key was overwritten or a key is missing. Check key existence and inspect update logic.
Null returned from a map lookup The key is absent or the stored value is null in a nullable-valued map. Use appropriate null handling and check key membership when necessary.
Modification method is unavailable The variable is typed as a read-only List, Set, or Map. Use the appropriate mutable interface when modification is required.
Unexpected iteration order The collection implementation does not guarantee the expected order. Use an ordered collection or sort the result explicitly.
Sorting changes the original array The in-place sort operation mutates the array. Copy the array before sorting if the original order must be preserved.
Equality checks return unexpected results for arrays Array == checks reference equality rather than structural content equality. Use contentEquals() for array content comparison.

Comparing Array Contents Correctly

val first = arrayOf(1, 2, 3)
val second = arrayOf(1, 2, 3)

println(first == second)
println(first.contentEquals(second))

Output:

false
true

For arrays, use contentEquals() when you want to compare their contents. For nested arrays, use contentDeepEquals() where deep content comparison is required.

20. Best Practices for Working with Collections

  • Choose an array when you need a fixed-size structure or compatibility with an API that requires arrays.
  • Choose a List when order matters and duplicate values are acceptable.
  • Choose a Set when values must be unique.
  • Choose a Map when values should be retrieved using unique keys.
  • Prefer read-only collection interfaces when mutation is not required.
  • Use val by default for references that should not be reassigned.
  • Validate indexes before accessing array or list elements when indexes come from user input.
  • Use map(), filter(), and other collection operations to express transformations clearly.
  • Do not depend on Set or Map iteration order unless the chosen implementation provides the required behavior.
  • Use meaningful data classes instead of loosely structured maps when representing complex domain objects.
  • Avoid changing a mutable collection while iterating over it unless the operation is explicitly supported.
  • Use efficient data structures appropriate to the size and access patterns of your data.
  • Use persistent Android storage when data must survive app restarts.

21. Practical Exercises

Exercise 1: Array Basics

Create an array of five integers. Print the first element, last element, array size, and all elements using a loop.

Exercise 2: Update Array Values

Create an array of student marks, update one mark, and print the updated array.

Exercise 3: Shopping List

Create a mutable list of five shopping items. Add two items, remove one item, and print the final list.

Exercise 4: Filter Scores

Create a list of marks and use filter() to return all marks greater than or equal to 60.

Exercise 5: Remove Duplicates

Create a list containing duplicate city names. Convert it into a Set and compare the collection sizes.

Exercise 6: Set Operations

Create two Sets of numbers and calculate their union, intersection, and difference.

Exercise 7: Student Map

Create a Map associating student names with marks. Retrieve a student's mark and check whether a given name exists.

Exercise 8: Word Counter

Create a list of repeated words and use a mutable Map to count how many times each word occurs.

Exercise 9: Product Filtering

Create a list of product objects and return only products whose prices are below a specified limit.

22. Mini Project: Student Record Manager

Build a simple Kotlin program that manages student records using a List, Set, and Map. This project demonstrates how different data structures can work together in an Android application.

Project Requirements

  • Use a data class to represent a student.
  • Store student records in a mutable list.
  • Maintain unique student names in a Set for a simple uniqueness check.
  • Store student marks in a Map keyed by student name.
  • Display all records and calculate the average mark.
  • Filter students who scored at least 60 marks.

Sample Solution

data class Student(
    val name: String,
    val marks: Int
)

fun main() {
    val students = mutableListOf(
        Student("Aarav", 85),
        Student("Priya", 92),
        Student("Rohan", 55),
        Student("Meera", 76)
    )

    val uniqueNames = students.map { it.name }.toSet()

    val marksByName = students.associate { student ->
        student.name to student.marks
    }

    val passedStudents = students.filter { it.marks >= 60 }

    val averageMarks = if (students.isNotEmpty()) {
        students.map { it.marks }.average()
    } else {
        0.0
    }

    println("Unique students: $uniqueNames")
    println("Marks by student: $marksByName")
    println("Passed students: ${passedStudents.map { it.name }}")
    println("Average marks: $averageMarks")
}

Expected output:

Unique students: [Aarav, Priya, Rohan, Meera]
Marks by student: {Aarav=85, Priya=92, Rohan=55, Meera=76}
Passed students: [Aarav, Priya, Meera]
Average marks: 77.0

Project Learning Outcomes

  • Understand when to use different Kotlin data structures.
  • Represent structured information using a data class.
  • Filter and transform collections.
  • Use a Set to maintain unique values.
  • Use a Map to retrieve values by key.
  • Calculate summary information from collection data.

23. Interview Questions and Answers

Q1. What is an array in Kotlin?

Answer: An array stores a fixed number of elements of a compatible type. Its elements are ordered and accessed through indexes.

Q2. What is the difference between an array and a list?

Answer: An array has a fixed size, while a mutable list can grow or shrink. Lists also provide collection operations and read-only or mutable interfaces.

Q3. What is the difference between List and MutableList?

Answer: List exposes read-only operations through its reference, while MutableList provides methods to add, remove, and update elements.

Q4. Can a List contain duplicate values?

Answer: Yes. A List preserves element order and allows duplicate values.

Q5. What is a Set used for?

Answer: A Set stores unique elements and is useful when duplicate values are not required.

Q6. What is the difference between a Set and a List?

Answer: A List is ordered and allows duplicates. A Set enforces uniqueness, and its iteration order depends on the implementation.

Q7. What is a Map in Kotlin?

Answer: A Map stores key-value pairs. Each key is unique, but multiple keys can have equal values.

Q8. What happens when you add an existing key to a MutableMap?

Answer: Assigning a new value to an existing key replaces its previous value instead of creating a duplicate key.

Q9. What is the purpose of map() and filter()?

Answer: map() transforms each element into a new value, while filter() selects elements that satisfy a condition.

Q10. How do you remove duplicates from a list?

Answer: Use distinct() to produce a list containing unique elements or toSet() to convert the elements into a Set.

Q11. How do you compare two arrays by content?

Answer: Use contentEquals() for content equality. The == operator on arrays checks whether the references are equal.

Q12. Can a val MutableList be modified?

Answer: Yes. The val keyword prevents reassignment of the list reference, but the contents of a MutableList can still be changed.

Q13. How do you retrieve a value from a Map?

Answer: Use the key access operator, such as map["username"]. The result may be null if the key is missing or if a nullable value is stored.

Q14. Why are collections useful in Android development?

Answer: Collections make it easier to manage lists of users, products, API results, preferences, and other dynamic data displayed or processed by an application.

24. Quick Revision Checklist

  • Understand arrays and zero-based indexing.
  • Create arrays with arrayOf() and primitive array constructors.
  • Access and update array elements safely.
  • Use Lists for ordered collections that may contain duplicates.
  • Use MutableLists when elements need to be added, removed, or updated.
  • Use Sets to prevent duplicate elements.
  • Use Maps to associate unique keys with values.
  • Understand the difference between read-only and mutable collection interfaces.
  • Practice collection operations such as map(), filter(), distinct(), and sorted().
  • Convert between arrays and collections when needed.
  • Handle missing map values and invalid indexes safely.
  • Apply collections to practical Android application scenarios.

25. Official Learning Resources

Conclusion

Arrays, Lists, Sets, and Maps are fundamental tools for managing data in Kotlin. Arrays are appropriate for fixed-size indexed data, Lists support ordered collections, Sets maintain unique elements, and Maps associate keys with values.

Understanding their differences helps Android developers choose suitable data structures, process application data effectively, reduce unnecessary duplication, and build maintainable application logic. Practise the examples and mini project to strengthen your Kotlin programming skills.

Continue learning with the JustAcademy Android App Development Course, explore the JustAcademy homepage, or register for a course demo.

Previous Next
whatsapp